<template>
  <div class="content">
    <el-card class="box-card head-card">
      <el-button
        type="primary"
        v-if="departmentShow"
        @click="departmentVisible = true"
        icon="el-icon-plus"
        >添加公司/船舶</el-button
      >
      <el-button type="primary" icon="el-icon-plus" @click="addDepartment"
        >添加设备</el-button
      >
      <el-button type="primary" @click="delDepartment">设备管理</el-button>
    </el-card>
    <div class="primary-content">
      <el-card class="box-card" style="width: 25%">
        <!-- 
          :default-expand-all="true" -->
        <el-tree
          node-key="id"
          :data="departmentData"
          :props="departmentProps"
          @node-click="departmentClick"
        >
        </el-tree>
      </el-card>
      <el-card class="box-card" style="width: 74%">
        <el-form
          :model="ruleForm"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label-width="120px" label="父级公司">
            <el-select
              class="main-select-tree"
              ref="selectTree"
              style="width: 100%"
              placeholder="请选择父级公司"
              clearable
              v-model="ruleForm.parentName"
            >
              <el-option :label="1" :value="2" style="display: none" />
              <el-tree
                :data="departmentData"
                :props="departmentProps"
                @node-click="departmentChange"
              ></el-tree>
            </el-select>
          </el-form-item>
          <el-form-item label-width="120px" label="公司/船舶名称">
            <el-input
              v-model="ruleForm.deptName"
              placeholder="请输入公司/船舶名称"
            ></el-input>
          </el-form-item>
          <el-form-item label-width="120px" label="公司/船舶类型">
            <el-select
              v-model="ruleForm.kind"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option label="公司" value="0"> </el-option>
              <el-option label="船队" value="2"> </el-option>
              <el-option label="船舶" value="1"> </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item
            label-width="120px"
            label="Ai识别Id"
            v-if="ruleForm.kind == 1 || ruleForm.kind == '船舶'"
          >
            <el-input
              v-model="ruleForm.boxId"
              placeholder="请输入Ai识别Id"
            ></el-input>
          </el-form-item> -->
          <el-form-item
            label="船舶MMSI"
            label-width="120px"
            v-if="ruleForm.kind == 1 || ruleForm.kind == '船舶'"
          >
            <el-input
              v-model="ruleForm.mmsi"
              placeholder="请输入船舶MMSI"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="船舶NMMSI"
            label-width="120px"
            v-if="ruleForm.kind == 1 || ruleForm.kind == '船舶'"
          >
            <el-input
              v-model="ruleForm.nmmsi"
              placeholder="请输入船舶NMMSI"
            ></el-input>
          </el-form-item>
          <el-form-item label-width="120px" label="备注">
            <el-input
              type="textarea"
              placeholder="请输入备注"
              :rows="6"
              v-model="ruleForm.remark"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(0)"
              >修改并保存</el-button
            >
            <!-- <el-button @click="submitForm(1)">重置</el-button> -->
            <el-button @click="submitForm(2)">删除</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <!-- 添加表单 -->
    <el-dialog
      title="添加公司/船舶"
      :visible.sync="departmentVisible"
      width="45%"
    >
      <el-form
        :model="addRuleForm"
        :rules="rules"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label-width="120px" label="父级公司">
          <el-select
            class="main-select-tree"
            disabled
            ref="selectTree"
            style="width: 100%"
            placeholder="请选择父级公司"
            clearable
            v-model="addRuleForm.parentName"
          >
            <el-option :label="1" :value="2" style="display: none" />
            <!-- <el-tree
              accordion
              show-checkbox
              :data="departmentData"
              :props="departmentProps"
              @check-change="addDepartmentChange"
            ></el-tree> -->
            <el-tree
              :data="departmentData"
              :props="departmentProps"
              @node-click="addDepartmentChange"
            ></el-tree>
          </el-select>
        </el-form-item>
        <el-form-item label-width="120px" label="公司/船舶名称" prop="deptName">
          <el-input
            v-model="addRuleForm.deptName"
            placeholder="请输入公司/船舶名称"
          ></el-input>
        </el-form-item>
        <el-form-item label-width="120px" label="公司/船舶类型" prop="kind">
          <el-select
            v-model="addRuleForm.kind"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option label="公司" value="0"> </el-option>
            <el-option label="船队" value="2"> </el-option>
            <el-option label="船舶" value="1"> </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item
          label="Ai识别Id"
          label-width="120px"
          v-if="addRuleForm.kind == 1 || addRuleForm.kind == '船舶'"
        >
          <el-input
            v-model="addRuleForm.boxId"
            placeholder="请输入Ai识别Id"
          ></el-input>
        </el-form-item> -->
        <el-form-item
          label="船舶MMSI"
          label-width="120px"
          v-if="addRuleForm.kind == 1 || addRuleForm.kind == '船舶'"
        >
          <el-input
            v-model="addRuleForm.mmsi"
            placeholder="请输入船舶MMSI"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="船舶NMMSI"
          label-width="120px"
          v-if="addRuleForm.kind == 1 || addRuleForm.kind == '船舶'"
        >
          <el-input
            v-model="addRuleForm.nmmsi"
            placeholder="请输入船舶NMMSI"
          ></el-input>
        </el-form-item>
        <el-form-item label-width="120px" label="备注">
          <el-input
            type="textarea"
            placeholder="请输入备注"
            :rows="6"
            v-model="addRuleForm.remark"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addSubmitForm(0)"
            >创建并保存</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 设备管理 -->
    <el-dialog
      :title="departmentItem.deptName || '--'"
      :visible.sync="manageVisible"
      width="70%"
      :center="false"
    >
      <!-- select -->
      <div class="select-content">
        <span>设备名称：</span>
        <el-input
          v-model="select.query"
          style="width: 300px; margin-right: 20px"
          placeholder="请输入设备名称"
        />
        <span>是否在线：</span>
        <el-select v-model="select.online" placeholder="请选择">
          <el-option label="全部" value="" />
          <el-option label="在线" value="true" />
          <el-option label="离线" value="false" />
        </el-select>
        <el-button
          style="margin-left: 20px"
          type="primary"
          @click="selectDepartment"
          >查询</el-button
        >
      </div>
      <!-- end -->
      <el-table
        :data="departmentChannelList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" v-if="managetype == 0">
        </el-table-column>
        <el-table-column prop="name" label="名称" min-width="160" />
        <el-table-column prop="deviceId" label="设备编号" min-width="180" />
        <el-table-column prop="manufacturer" label="厂家" min-width="120" />
        <el-table-column
          prop="transport"
          label="信令传输模式"
          min-width="120"
        />
        <el-table-column
          prop="keepaliveTime"
          label="最近心跳"
          min-width="160"
        />
        <el-table-column prop="registerTime" label="最近注册" min-width="160" />
        <el-table-column prop="channelCount" label="通道数" min-width="120" />
        <el-table-column label="状态" min-width="120">
          <template slot-scope="scope">
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium" v-if="scope.row.onLine">在线</el-tag>
              <el-tag size="medium" type="info" v-if="!scope.row.onLine"
                >离线</el-tag
              >
            </div>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="120">
          <template slot-scope="scope">
            <el-popconfirm
              :title="'确认移除' + scope.row.name + '吗？'"
              v-if="managetype == 0"
              @confirm="deleteDepartmentChanne(scope.$index, scope.row)"
            >
              <el-button type="text" size="small" slot="reference">
                移除
              </el-button>
            </el-popconfirm>

            <el-button
              v-if="managetype == 1"
              @click.native.prevent="
                addDepartmentChanne(scope.$index, scope.row)
              "
              type="text"
              size="small"
            >
              添加
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="paging-content" v-if="managetype != 0">
        <el-pagination
          layout="prev, pager, next"
          :hide-on-single-page="true"
          :total="select.total"
          :page-size="select.count"
          @current-change="pagingDepartment"
        />
      </div>
    </el-dialog>
  </div>
</template>
  
  <script>
import uiHeader from "../layout/UiHeader.vue";

export default {
  name: "department",
  components: {
    uiHeader,
  },
  data() {
    return {
      departmentShow: false,
      select: { query: "", online: "", page: 1, count: 5, total: 0 },
      channelIds: "",
      manageVisible: false,
      managetype: -1, // 0:设备管理 1:添加设备
      departmentChannelList: [],
      departmentItem: {},
      departmentVisible: false,
      departmentData: [],
      departmentProps: {
        children: "children",
        label: "deptName",
      },
      rules: {
        deptName: [
          { required: true, message: "请输入公司/船舶名称", trigger: "blur" },
        ],
        kind: [
          { required: true, message: "请选择公司/船舶类型", trigger: "change" },
        ],
      },
      ruleForm: {
        deptName: "", // 部门名称
        parentId: "", // 父级ID
        parentName: "", // 父级名称
        remark: "", // 备注
        boxId: "", // 机顶盒id
        kind: "", // 部门类型
        mmsi: "",
        nmmsi: "",
      },
      addRuleForm: {
        deptName: "", // 部门名称
        parentId: "", // 父级ID
        parentName: "", // 父级名称
        remark: "", // 备注
        boxId: "", // 机顶盒id
        kind: "", // 部门类型
        mmsi: "",
        nmmsi: "",
      },
    };
  },
  mounted() {
    this.getDepartment();
  },
  methods: {
    // 获取部门树
    getDepartment() {
      const that = this;
      that
        .$axios({
          method: "get",
          url: `/api/department/tree`,
        })
        .then((res) => {
          if (res.data.code == 0) {
            that.departmentData = res.data.data;
            return;
          }
          this.$message.error(res.data.msg);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 点击部门树
    departmentClick(data, node, element) {
      this.departmentItem = data;
      this.departmentShow = true;
      this.getDepartmentById(data.id);
      this.addRuleForm.parentName = data.deptName;
      this.addRuleForm.parentId = data.id;
    },
    // 通过id获取部门
    getDepartmentById(id) {
      const that = this;
      that
        .$axios({
          method: "get",
          url: `/api/department/get-by-id?id=` + id,
        })
        .then((res) => {
          if (res.data.code == 0) {
            this.ruleForm.id = res.data.data.id; // 部门ID
            this.ruleForm.deptName = res.data.data.deptName; // 部门名称
            this.ruleForm.parentId = res.data.data.parentId; // 父级ID
            this.ruleForm.parentName = res.data.data.parentName; // 父级名称
            this.ruleForm.remark = res.data.data.remark; // 备注
            this.ruleForm.boxId = res.data.data.boxId; // 盒子Id
            this.ruleForm.kind =
              res.data.data.kind == 1
                ? "船舶"
                : res.data.data.kind == 0
                ? "公司"
                : "船队"; // 部门类型
            this.ruleForm.mmsi = res.data.data.mmsi; // mmsi
            this.ruleForm.nmmsi = res.data.data.nmmsi; // nmmsi
            return;
          }
          this.$message.error(res.data.msg);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 选择部门树
    departmentChange(data, checked, indeterminate) {
      this.ruleForm.parentName = data.deptName;
      this.ruleForm.parentId = data.id;
    },
    // 修改表单/重置表单/删除
    submitForm(type) {
      const that = this;
      if (type == 0) {
        if (
          this.ruleForm.id == "" ||
          this.ruleForm.id == undefined ||
          this.ruleForm.id == null
        ) {
          this.$message.warning("请选择左侧部门进行修改！");
          return;
        }
        this.ruleForm.kind =
          this.ruleForm.kind == "公司"
            ? 0
            : this.ruleForm.kind == "船舶"
            ? 1
            : this.ruleForm.kind == "船队"
            ? 2
            : this.ruleForm.kind;
        const formData = new FormData();
        for (const key in this.ruleForm) {
          if (key != "children") {
            formData.append(key, this.ruleForm[key]);
          }
        }
        that
          .$axios({
            method: "post",
            url: `/api/department/update-by-id`,
            data: formData,
            headers: {
              "Content-Type": "multipart/form-data", // 设置正确的 Content-Type
            },
          })
          .then((res) => {
            if (res.data.code == 0) {
              this.$message({
                message: "操作成功！",
                type: "success",
              });
              this.ruleForm = {
                deptName: "", // 部门名称
                parentId: "", // 父级ID
                parentName: "", // 父级名称
                remark: "", // 备注
                boxId: "", // 盒子Id
                kind: "", // 部门类型
              };
              this.getDepartment();
              return;
            }
            this.$message.error(res.data.msg);
          })
          .catch((error) => {
            console.log(error);
          });
      } else if (type == 1) {
        this.ruleForm = {
          id: "",
          deptName: "", // 部门名称
          parentId: "", // 父级ID
          parentName: "", // 父级名称
          remark: "", // 备注
          boxId: "", // 盒子Id
          kind: "", // 部门类型
        };
      } else if (type == 2) {
        that
          .$axios({
            method: "get",
            url: `/api/department/del-by-id?id=` + this.ruleForm.id,
          })
          .then((res) => {
            if (res.data.code == 0) {
              this.$message({
                message: "操作成功！",
                type: "success",
              });
              this.departmentShow = false;
              this.getDepartment();
              this.ruleForm = {
                deptName: "", // 部门名称
                parentId: "", // 父级ID
                parentName: "", // 父级名称
                remark: "", // 备注
                boxId: "", // 盒子Id
                kind: "", // 部门类型
              };
              return;
            }
            this.$message.error(res.data.msg);
          })
          .catch((error) => {
            console.log(error);
          });
      }
    },
    // 添加表单
    addSubmitForm() {
      const that = this;
      if (that.addRuleForm.deptName == "") {
        this.$message.error("请输入公司/船舶名称");
        return;
      } else if (that.addRuleForm.kind == "") {
        this.$message.error("请选择公司/船舶类型");
        return;
      }
      const formData = new FormData();
      for (const key in this.addRuleForm) {
        formData.append(key, this.addRuleForm[key]);
      }
      that
        .$axios({
          method: "post",
          url: `/api/department/add`,
          data: formData,
          headers: {
            "Content-Type": "multipart/form-data", // 设置正确的 Content-Type
          },
        })
        .then((res) => {
          this.departmentVisible = false;
          if (res.data.code == 0) {
            this.$message({
              message: "操作成功！",
              type: "success",
            });
            this.getDepartment();
            this.addRuleForm = {
              deptName: "", // 部门名称
              parentId: "", // 父级ID
              parentName: "", // 父级名称
              remark: "", // 备注
              boxId: "", // 盒子Id
              kind: "", // 部门类型
            };
            return;
          }
          this.$message.error(res.data.msg);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 选择部门树
    addDepartmentChange(data, checked, indeterminate) {
      this.addRuleForm.parentName = data.deptName;
      this.addRuleForm.parentId = data.id;
    },
    // 搜索设备 / 设备列表
    selectDepartment() {
      this.select.page = 1;
      this.addDepartment();
    },
    // 添加设备 / 设备列表
    addDepartment() {
      const that = this;
      if (
        this.departmentItem.children != undefined &&
        this.departmentItem.children.length == 0
      ) {
        let deptId = this.departmentItem.id; // 部门ID
        let query = this.select.query; // 查询内容
        let online = this.select.online; // 是否在线
        let page = this.select.page; // 当前页
        let count = this.select.count; // 每页条数
        that
          .$axios({
            method: "get",
            url: `/api/department/devices/unbound/dept-id?deptId=${deptId}&query=${query}&online=${online}&page=${page}&count=${count}`,
            data: page,
          })
          .then((res) => {
            if (res.data.code == 0) {
              this.departmentChannelList = [];
              if (res.data.data.list.length > 0) {
                this.manageVisible = true;
                this.managetype = 1;
                this.select.total = res.data.data.total;
                this.departmentChannelList = res.data.data.list;
              }
              this.$message.warning("当前暂无更多设备");
              return;
            }
            this.$message.error(res.data.msg);
          })
          .catch((error) => {
            console.log(error);
          });
        return;
      }
      this.$message.warning("请在最底层设备操作");
    },
    // 移除设备 / 设备列表
    delDepartment() {
      const that = this;
      if (
        this.departmentItem.children != undefined &&
        this.departmentItem.children.length == 0
      ) {
        that
          .$axios({
            method: "get",
            url: `/api/department/device/dept-id?id=` + this.departmentItem.id,
          })
          .then((res) => {
            if (res.data.code == 0) {
              this.departmentChannelList = [];
              if (res.data.data.length > 0) {
                this.manageVisible = true;
                this.managetype = 0;
                this.departmentChannelList = res.data.data;
              } else {
                this.$message.warning("当前部门下，暂无设备请先添加");
              }
              return;
            }
            this.$message.error(res.data.msg);
          })
          .catch((error) => {
            console.log(error);
          });
        return;
      }
      this.$message.warning("请在最底层设备操作");
    },
    // 分页
    pagingDepartment(val) {
      this.select.page = val;
      this.addDepartment();
    },
    // 移除设备
    deleteDepartmentChanne(index, rows) {
      if (this.channelIds.length > 0) {
        this.$confirm("当前选择多个设备，是否移除？")
          .then((_) => {
            let channelIds = this.channelIds.join(",");
            this.setDelChannel(channelIds);
            done();
          })
          .catch((_) => {});
        return;
      }
      this.setDelChannel(rows.id);
    },
    // 移除设备
    setDelChannel(channelIds) {
      const that = this;
      that
        .$axios({
          method: "get",
          url: `/api/department/remove/channel?channelIds=` + channelIds,
        })
        .then((res) => {
          if (res.data.code == 0) {
            this.$message.success("移除成功！");
            this.delDepartment();
            this.manageVisible = !this.manageVisible;
            return;
          }
          this.$message.error(res.data.msg);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 列表选中
    handleSelectionChange(val) {
      const that = this;
      that.channelIds = [];
      val.forEach((element) => {
        that.channelIds.push(element.id);
      });
    },
    // 添加设备
    addDepartmentChanne(index, rows) {
      const that = this;
      that
        .$axios({
          method: "get",
          url: `/api/department/channels/bound/dept-id?channelIds=${rows.id}&deptId=${this.departmentItem.id}`,
        })
        .then((res) => {
          if (res.data.code == 0) {
            this.$message.success("添加成功！");
            this.manageVisible = !this.manageVisible;
            return;
          }
          this.$message.error(res.data.msg);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // end
  },
};
</script>
  <style>
.paging-content {
  margin-top: 20px;
  text-align: right;
}
.select-content {
  padding: 10px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.content {
  width: 100%;
  padding: 20px 0;
}
.head-card {
  display: flex;
  margin-bottom: 20px;
}
.primary-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 70vh;
}
.primary-content .box-card {
  height: 100%;
}
.demo-ruleForm {
  width: 80%;
  margin: 0 auto;
}
</style>